package com.khanacademy;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class KhanAcademy extends ListActivity
{	
	private static final String DEBUG_TAG = "KhanAcademy: MAIN";
	final Handler handler = new Handler();
	private final int PROGRESS_DIALOG = 1;
	ArrayList<HashMap<String,Object>> playlistList = new ArrayList<HashMap<String,Object>>();
	SimpleAdapter simpleAdapter = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
		
        // set content view
        setContentView(R.layout.main);
        
        // display a progress dialog while fetching data
		showDialog(PROGRESS_DIALOG);
    		
        // new thread which downloads the data
    	new Thread()
   		{
    		@Override
    		public void run()
   			{
    			downloadData();
   				handler.post(loadLayout);
   			}
    	}.start();
    }

    // progress dialog
    @Override
    protected Dialog onCreateDialog(int id)
    {
    	if (id == PROGRESS_DIALOG)
    	{
    		Log.e(DEBUG_TAG, "Starting Progress Dialog...");
    		ProgressDialog dialog = new ProgressDialog(this);
    		dialog.setMessage("Downloading Categories...");
    		return dialog;
    	}
    	return super.onCreateDialog(id);
    }
    	
    // load the layout after the download thread is finished
    final Runnable loadLayout = new Runnable()
    {
    	public void run()
    	{
    		// set the list adapter
        	simpleAdapter = new SimpleAdapter(KhanAcademy.this, playlistList, R.layout.main_list, new String[] {"title"}, new int[] {R.id.title});
            setListAdapter(simpleAdapter);
    		
        	// remove progress dialog
    		dismissDialog(PROGRESS_DIALOG);
    	}
    };

    // gets the list item when clicked
    @Override
    public void onListItemClick(ListView l, View v, int position, long id)
    {
    	// get the movie id using the name as a key
    	HashMap<String,Object> item = playlistList.get(position);
		Intent i = new Intent(KhanAcademy.this, Category.class);
		i.putExtra("TITLE", item.get("title").toString());
		i.putExtra("PLAYLIST", item.get("playlist").toString());
		i.putExtra("COUNT", Integer.parseInt(item.get("count").toString()));
		startActivity(i);
    }

    // download data from the internet
    public void downloadData()
    {		
    	try
    	{
    		// need to stick multiple lists together if there are more than 50 playlists (which there are now)
    		for (int c = 1; c < 55; c+=50)
    		{		
    			// get the data from the internet
    			JSONObject jsonObject = JSONParser.getJSONObject("http://gdata.youtube.com/feeds/api/users/khanacademy/playlists?v=2&start-index="+c+"&max-results=50&alt=json");
    			JSONArray entryArray = jsonObject.getJSONObject("feed").getJSONArray("entry");

    			// parse the data
    			for (int i = 0; i < entryArray.length(); i++)
    			{									
    				// create a list item
    				HashMap<String,Object> item = new HashMap<String,Object>();
    			
    				// get this json object from the array
    				JSONObject object = null;
    				try { object = entryArray.getJSONObject(i); }
    				catch (JSONException e) { Log.d(DEBUG_TAG, "JSONException (Object)", e); }
    	        
    				// add the object properties to a hashmap
    				item.put("title", object.getJSONObject("title").get("$t").toString());
    				item.put("playlist", object.getJSONObject("yt$playlistId").get("$t").toString());
    				int count = Integer.parseInt(object.getJSONObject("yt$countHint").get("$t").toString());
    				item.put("count", count);
    				if (count != 0) 
    					playlistList.add(item);
    			}
    		}
    	}
    	catch (JSONException e) { Log.e(DEBUG_TAG, "JSONException in downloadData", e); }
    	catch (NullPointerException e) { Log.e(DEBUG_TAG, "NullPointerException in downloadData", e); }
   	}
}